package com.study.manage.dal;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import com.study.manage.domain.Blog;
import com.study.manage.domain.EvaluateNew;
import com.study.manage.domain.enumm.EvaluateNewType;
import com.study.manage.domain.enumm.LiveDieState;

public interface EvaluateNewRepository extends PagingAndSortingRepository<EvaluateNew, Long> {

    Page<EvaluateNew> findByEvaluateIdAndState(Long evaluateId, LiveDieState state,
            Pageable pageable);


    int countByEvaluateIdAndState(Long evaluateId, LiveDieState state);


    List<EvaluateNew> findByEvaluateIdAndState(Long evaluateId, LiveDieState state);

    @Query("select t from EvaluateNew t,News n where n.id=t.newsId and n.blogId=:blogId and t.state=:state")
    List<EvaluateNew> findByBlogIdAndState(@Param("blogId") Long blogId,
            @Param("state") LiveDieState state);

    List<EvaluateNew> findByNewsIdAndState(Long newsId, LiveDieState state);

    @Query("select b from EvaluateNew t,News n,Blog b where t.newsId=n.id and b.id=n.blogId and t.evaluateId=:evaluateId and t.state=:state")
    Page<Blog> findBlogByEvaluateIdAndState(@Param("evaluateId") Long evaluateId,
            @Param("state") LiveDieState state, Pageable pageable);


    @Modifying
    @Query("update EvaluateNew set state=1 where newsId=:newsId and state=0")
    Integer deleteByNewsId(@Param("newsId") Long newsId);

    List<EvaluateNew> findByEvaluateIdAndNewsId(Long evaluateId, Long newsId);

    @Query("select en from News t, EvaluateNew en where en.newsId=t.id and en.evaluateId=:evaluateId and (t.type=:type or :type is null) and t.state=0 and en.state=0 order by en.isTop desc,en.modifiedAt desc")
    Page<EvaluateNew> findByEvaluateIdAndTypeAndLive(@Param("evaluateId") Long evaluteId,
            @Param("type") EvaluateNewType type, Pageable pageable);

}
